const css = require('./login.scss');
const Reg = require('../../mod/reg');
const Ajax = require('../../mod/webajax');
const Toast = require('../../mod/toast');

$('#inputPhone').on('focus', function(){
  $(this).parents('.form-group').removeClass('has-error');
  $('.tip-phone').text('');
} );

$('#inputPassword').on('focus', function(){
  $(this).parents('.form-group').removeClass('has-error');
  $('.tip-password').text('');
} );

// 登录login.js
$('#J_Login').on('click', async function(e){

  e.preventDefault();

  let phone_value = $('#inputPhone').val().trim();
  let password_value = $('#inputPassword').val();

  // 手机号
  if( phone_value.length == 0 ){
    $('.tip-phone').text('手机号不能为空');
    $('.tip-phone').parents('.form-group').addClass('has-error');
    return false;
  }

  if( !Reg.phone.test( phone_value ) ){
    $('.tip-phone').text('手机号格式有误，11位数字');
    $('.tip-phone').parents('.form-group').addClass('has-error');
    return false;
  }

  // 密码框
  if( password_value.length == 0 ){
    $('.tip-password').text('密码不能为空');
    $('.tip-password').parents('.form-group').addClass('has-error');
    return false;
  }

  try{
    let json = await Ajax({
      type:'POST',
      url:'/login',
      data:{
        password_hash:password_value,
        mobile: phone_value,
      },
    });

    if( json.result != 'error' ){
      Toast( json.msg, function(){
          // alert('可以跳转');
          window.location.href='/admin.html';
      } );

      //
    }else{
      // alert(json.msg);
      Toast(json.msg);
    }

  }catch(e){
    Toast(e);
  }


  /* $.ajax({
    type:'POST',
    url:'/login',
    dataType: "json",
    data:{
      password_hash:password_value,
      mobile: phone_value,
    },
    crossDomain: true,
    xhrFields: {
      withCredentials: true
    },
    success(json){

      if( json.result != 'error' ){
        window.location.href='/role.html';
      }else{
        alert(json.msg);
      }
    },
    error(e){
      console.log(e);
    }
  }); */

} );
